"""
AI助手管理路由
提供对话框的动态控制功能，包括大小调整、按钮配置、交互模式和透明度调节
"""

from typing import List, Optional

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session

from config.database import get_db_session
from pojo.ai_web_dialog import (
    AIWebDialogCreate, AIWebDialogUpdate,
    AIWebDialogResponse, AIWebDialogListResponse,
    InteractiveMode,
    DialogSize, ButtonConfig
)
from pojo.ai_web_dialog_model import AIWebDialogModel
from pojo.ai_web_scene_model import AIWebSceneModel

router = APIRouter()


@router.post("/", response_model=AIWebDialogResponse, summary="创建AI对话框配置")
async def create_dialog(
        dialog_data: AIWebDialogCreate,
        db: Session = Depends(get_db_session)
):
    """
    创建新的AI对话框配置
    
    - **scene_id**: 场景ID
    - **dialog_size**: 对话框尺寸配置
    - **buttons**: 按钮集合配置
    - **interactive_mode**: 交互模式(1=对话框,2=语音通话,3=视频聊天)
    - **transparency**: 对话框透明度(0-100)
    """
    # 验证场景是否存在
    scene = db.query(AIWebSceneModel).filter(AIWebSceneModel.scene_id == dialog_data.scene_id).first()
    if not scene:
        raise HTTPException(status_code=404, detail=f"场景 {dialog_data.scene_id} 不存在")

    # 检查该场景是否已有对话框配置
    existing_dialog = db.query(AIWebDialogModel).filter(
        AIWebDialogModel.scene_id == dialog_data.scene_id
    ).first()
    if existing_dialog:
        raise HTTPException(status_code=400, detail=f"场景 {dialog_data.scene_id} 已存在对话框配置")

    # 创建对话框配置
    dialog_model = AIWebDialogModel(
        scene_id=dialog_data.scene_id,
        agent_ids=dialog_data.agent_ids,
        dialog_size=dialog_data.dialog_size.model_dump(),
        buttons=[button.model_dump() for button in dialog_data.buttons],
        interactive_mode=dialog_data.interactive_mode,
        transparency=dialog_data.transparency
    )

    db.add(dialog_model)
    db.commit()
    db.refresh(dialog_model)

    return AIWebDialogResponse.model_validate(dialog_model)


@router.get("/", response_model=AIWebDialogListResponse, summary="获取对话框配置列表")
async def get_dialogs(
        scene_id: Optional[str] = Query(None, description="场景ID"),
        interactive_mode: Optional[int] = Query(None, ge=1, le=3, description="交互模式"),
        page: int = Query(1, ge=1, description="页码"),
        page_size: int = Query(20, ge=1, le=100, description="每页数量"),
        db: Session = Depends(get_db_session)
):
    """
    获取对话框配置列表，支持多种筛选条件
    """
    query = db.query(AIWebDialogModel)

    # 应用筛选条件
    if scene_id:
        query = query.filter(AIWebDialogModel.scene_id == scene_id)

    if interactive_mode is not None:
        query = query.filter(AIWebDialogModel.interactive_mode == interactive_mode)

    # 分页
    total_count = query.count()
    dialogs = query.offset((page - 1) * page_size).limit(page_size).all()

    return AIWebDialogListResponse(
        total_count=total_count,
        dialogs=[AIWebDialogResponse.model_validate(dialog) for dialog in dialogs]
    )


@router.get("/{dialog_id}", response_model=AIWebDialogResponse, summary="获取对话框配置详情")
async def get_dialog(
        dialog_id: int,
        db: Session = Depends(get_db_session)
):
    """
    根据ID获取对话框配置详情
    """
    dialog = db.query(AIWebDialogModel).filter(AIWebDialogModel.id == dialog_id).first()
    if not dialog:
        raise HTTPException(status_code=404, detail=f"对话框配置 {dialog_id} 不存在")

    return AIWebDialogResponse.model_validate(dialog)


@router.get("/scene/{scene_id}", response_model=AIWebDialogResponse, summary="根据场景ID获取对话框配置")
async def get_dialog_by_scene(
        scene_id: str,
        db: Session = Depends(get_db_session)
):
    """
    根据场景ID获取对话框配置
    """
    dialog = db.query(AIWebDialogModel).filter(AIWebDialogModel.scene_id == scene_id).first()
    if not dialog:
        raise HTTPException(status_code=404, detail=f"场景 {scene_id} 的对话框配置不存在")

    return AIWebDialogResponse.model_validate(dialog)


@router.put("/{dialog_id}", response_model=AIWebDialogResponse, summary="更新对话框配置")
async def update_dialog(
        dialog_id: int,
        dialog_data: AIWebDialogUpdate,
        db: Session = Depends(get_db_session)
):
    """
    更新对话框配置，支持部分更新
    """
    dialog = db.query(AIWebDialogModel).filter(AIWebDialogModel.id == dialog_id).first()
    if not dialog:
        raise HTTPException(status_code=404, detail=f"对话框配置 {dialog_id} 不存在")

    # 更新字段
    update_data = dialog_data.model_dump(exclude_unset=True)

    if "agent_ids" in update_data:
        dialog.agent_ids = update_data["agent_ids"]

    if "dialog_size" in update_data:
        # 检查是否已经是字典格式
        if hasattr(update_data["dialog_size"], 'model_dump'):
            dialog.dialog_size = update_data["dialog_size"].model_dump()
        else:
            dialog.dialog_size = update_data["dialog_size"]

    if "buttons" in update_data:
        # 检查按钮是否已经是字典格式
        buttons_data = update_data["buttons"]
        if buttons_data and hasattr(buttons_data[0], 'model_dump'):
            dialog.buttons = [button.model_dump() for button in buttons_data]
        else:
            dialog.buttons = buttons_data

    if "interactive_mode" in update_data:
        dialog.interactive_mode = update_data["interactive_mode"]

    if "transparency" in update_data:
        dialog.transparency = update_data["transparency"]

    db.commit()
    db.refresh(dialog)

    return AIWebDialogResponse.model_validate(dialog)


@router.delete("/{dialog_id}", summary="删除对话框配置")
async def delete_dialog(
        dialog_id: int,
        db: Session = Depends(get_db_session)
):
    """
    删除对话框配置
    """
    dialog = db.query(AIWebDialogModel).filter(AIWebDialogModel.id == dialog_id).first()
    if not dialog:
        raise HTTPException(status_code=404, detail=f"对话框配置 {dialog_id} 不存在")

    db.delete(dialog)
    db.commit()

    return {"message": f"对话框配置 {dialog_id} 删除成功"}


# ==================== 动态控制功能 ====================

@router.put("/{dialog_id}/size", response_model=AIWebDialogResponse, summary="动态调整对话框大小")
async def update_dialog_size(
        dialog_id: int,
        size_data: DialogSize,
        db: Session = Depends(get_db_session)
):
    """
    动态调整对话框大小
    """
    dialog = db.query(AIWebDialogModel).filter(AIWebDialogModel.id == dialog_id).first()
    if not dialog:
        raise HTTPException(status_code=404, detail=f"对话框配置 {dialog_id} 不存在")

    dialog.dialog_size = size_data.model_dump()
    db.commit()
    db.refresh(dialog)

    return AIWebDialogResponse.model_validate(dialog)


@router.put("/{dialog_id}/buttons", response_model=AIWebDialogResponse, summary="动态配置对话框按钮")
async def update_dialog_buttons(
        dialog_id: int,
        buttons: List[ButtonConfig],
        db: Session = Depends(get_db_session)
):
    """
    动态配置对话框按钮
    """
    dialog = db.query(AIWebDialogModel).filter(AIWebDialogModel.id == dialog_id).first()
    if not dialog:
        raise HTTPException(status_code=404, detail=f"对话框配置 {dialog_id} 不存在")

    # 验证按钮ID唯一性
    button_ids = [button.id for button in buttons]
    if len(button_ids) != len(set(button_ids)):
        raise HTTPException(status_code=400, detail="按钮ID必须唯一")

    dialog.buttons = [button.model_dump() for button in buttons]
    db.commit()
    db.refresh(dialog)

    return AIWebDialogResponse.model_validate(dialog)


@router.post("/{dialog_id}/buttons", response_model=AIWebDialogResponse, summary="添加对话框按钮")
async def add_dialog_button(
        dialog_id: int,
        button: ButtonConfig,
        db: Session = Depends(get_db_session)
):
    """
    添加新的对话框按钮
    """
    dialog = db.query(AIWebDialogModel).filter(AIWebDialogModel.id == dialog_id).first()
    if not dialog:
        raise HTTPException(status_code=404, detail=f"对话框配置 {dialog_id} 不存在")

    # 检查按钮ID是否已存在
    if dialog.get_button_by_id(button.id):
        raise HTTPException(status_code=400, detail=f"按钮ID {button.id} 已存在")

    if not dialog.add_button(button.model_dump()):
        raise HTTPException(status_code=400, detail="添加按钮失败")

    db.commit()
    db.refresh(dialog)

    return AIWebDialogResponse.model_validate(dialog)


@router.delete("/{dialog_id}/buttons/{button_id}", response_model=AIWebDialogResponse, summary="删除对话框按钮")
async def remove_dialog_button(
        dialog_id: int,
        button_id: str,
        db: Session = Depends(get_db_session)
):
    """
    删除指定的对话框按钮
    """
    dialog = db.query(AIWebDialogModel).filter(AIWebDialogModel.id == dialog_id).first()
    if not dialog:
        raise HTTPException(status_code=404, detail=f"对话框配置 {dialog_id} 不存在")

    if not dialog.remove_button(button_id):
        raise HTTPException(status_code=404, detail=f"按钮 {button_id} 不存在")

    db.commit()
    db.refresh(dialog)

    return AIWebDialogResponse.model_validate(dialog)


@router.put("/{dialog_id}/interactive", response_model=AIWebDialogResponse, summary="动态调整交互模式")
async def update_interactive_mode(
        dialog_id: int,
        interactive_mode: int = Query(..., ge=1, le=3, description="交互模式(1=对话框,2=语音通话,3=视频聊天)"),
        db: Session = Depends(get_db_session)
):
    """
    动态调整对话框交互模式
    
    模式说明：
    - 1: 对话框
    - 2: 语音通话
    - 3: 视频聊天
    """
    dialog = db.query(AIWebDialogModel).filter(AIWebDialogModel.id == dialog_id).first()
    if not dialog:
        raise HTTPException(status_code=404, detail=f"对话框配置 {dialog_id} 不存在")

    dialog.interactive_mode = interactive_mode

    db.commit()
    db.refresh(dialog)

    return AIWebDialogResponse.model_validate(dialog)


@router.put("/{dialog_id}/transparency", response_model=AIWebDialogResponse, summary="动态调整对话框透明度")
async def update_dialog_transparency(
        dialog_id: int,
        transparency: int = Query(..., ge=0, le=100, description="透明度(0-100)"),
        db: Session = Depends(get_db_session)
):
    """
    动态调整对话框透明度
    """
    dialog = db.query(AIWebDialogModel).filter(AIWebDialogModel.id == dialog_id).first()
    if not dialog:
        raise HTTPException(status_code=404, detail=f"对话框配置 {dialog_id} 不存在")

    dialog.transparency = transparency
    db.commit()
    db.refresh(dialog)

    return AIWebDialogResponse.model_validate(dialog)


# ==================== 辅助功能 ====================

@router.get("/{dialog_id}/modes", summary="获取对话框交互模式详情")
async def get_dialog_modes(
        dialog_id: int,
        db: Session = Depends(get_db_session)
):
    """
    获取对话框交互模式的详细信息
    """
    dialog = db.query(AIWebDialogModel).filter(AIWebDialogModel.id == dialog_id).first()
    if not dialog:
        raise HTTPException(status_code=404, detail=f"对话框配置 {dialog_id} 不存在")

    return {
        "dialog_id": dialog_id,
        "interactive_mode": {
            "value": dialog.interactive_mode,
            "name": InteractiveMode.get_mode_name(dialog.interactive_mode)
        }
    }
